package mpcs.mylibs.core
{
	import com.google.maps.LatLng;
	import com.google.maps.services.ClientGeocoder;
	import com.google.maps.services.ClientGeocoderOptions;
	import com.google.maps.services.GeocodingEvent;
	
	import flash.events.ProgressEvent;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	import mpcs.ApplicationFacade;
	import mpcs.NotiConst;
	import mpcs.mylibs.data.Packet;
	
	import mx.collections.ArrayCollection;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;

	public class Server {
		
		private var _serverSocket:ServerSocket;
		private var _clientSocket:Socket;
		
		/**
		 * 存放的数据格式为： previous:Object
		 * <br/> {mobile: mobile, tsp: tsp, lat: lat, lng: lng, location: null, accuracy: accuracy};
		 * <br/>代表的含义依次是：手机号，时间戳，经度，维度，地理位置，精确度
		 * <br/>数据类型依次是：
		 * <br/> mobile  String()
		 * <br/> tsp String()
		 * <br/> lat Double()
		 * <br/> lng Double()
		 * <br/> accuracy Double()
		 */		
		public var locations:ArrayCollection;
		
		public function Server() {
			locations = new ArrayCollection();
		}
		
		public function init():void{
			_serverSocket = new ServerSocket();
			_serverSocket.addEventListener(ServerSocketConnectEvent.CONNECT, onServerSocketConnect);
			
			// 绑定的接收位置数据的端口
			_serverSocket.bind(31337, "0.0.0.0");
			_serverSocket.listen();
			trace("位置接收更新服务器成功启动 ... listenning on 31337 ...  Server ... ");
		}
		
		private function onServerSocketConnect(event:ServerSocketConnectEvent):void{
			if(_clientSocket != null){
				_clientSocket.removeEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData);
			}
			_clientSocket = event.socket;
			_clientSocket.addEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData, false, 0, true);
			trace("接入一个连接，编号 = " + Socket(event.socket).remotePort + " 。。。");
		}
		
		private function onClientSocketData(event:ProgressEvent):void{
			var buffer:ByteArray = new ByteArray();
			var mobile:String = null;
			var tsp:String = null;
			var lat:Number = 0;
			var lng:Number = 0;
			var accuracy:Number = 0;
			var previous:Object = null;
			_clientSocket.readBytes(buffer, 0, _clientSocket.bytesAvailable);
			
			var packet:Packet = new Packet(buffer);
			
			// 验证接收到的位置数据是否合法，合法则解析、分包
			if(packet.readInt() == 999999){
				mobile = packet.readString();
				tsp = packet.readString();
				lat = packet.readDouble();
				lng = packet.readDouble();
				accuracy = packet.readDouble();
				previous = {mobile: mobile, tsp: tsp, lat: lat, lng: lng, location: null, accuracy: accuracy};
				locations.addItem(previous);
				
				trace("有新的位置数据 ... Server ... onClientSocketData ... 发送位置更新的通知 ... ");
				// 发送位置更新的通知
				ApplicationFacade.getInstance().sendNotification( NotiConst.POSITION_LIST_CHANGE, previous);
				
			}else{
				trace(packet.array().toString());
			}
		}
		
	}
}